package de.itagile.hypersphere

class Relation {
	
	def relation
	
	public Relation(def relation) {
		this.relation = relation
	}
	
	public int hashCode() {
		return relation.ejbrelationname.hashCode();
	}
	
	public boolean equals(def other) {
		if (relation.ejbrelationname == other.relation.ejbrelationname)
			return true
		else
			return false
	}
	
	public getEntity(def name) {
		return relation.ejbrelationshiprole.relationshiprolesource.ejbname.
			find{it.text() == name}
	}
	
	public getEntityName(def name) {
		return getEntity(name).text()
	}
	
	public getOppositeEntity(def name) {
		def ejbname = relation.ejbrelationshiprole.relationshiprolesource.ejbname
		if (isSelfReferencing(ejbname))
			return ejbname[0]
		else
			return ejbname.find{it.text() != name}
	}
	
	private isSelfReferencing(def ejbname) {
		return (ejbname[0].text() == ejbname[1].text())  
	}
	
	public getOppositeEntityName(def name) {
		return getOppositeEntity(name).text()
	}
	
	public getType(def name) {
		return getMultiplicity(getEntity(name)) + "To" + getMultiplicity(getOppositeEntity(name))
	}
	
	public getCollection(def name) {
		def result = getEntity(name).'..'.'..'.cmrfield.cmrfieldtype?.text()
		if (result == null)
			result = ""
		return result
	}
	
	public getMultiplicity(def entityName) {
		return entityName.'..'.'..'.multiplicity.text()
	}
}